/**
 *
 * Copyright (c) 2014-2017 All Rights Reserved.
 */
package org.tinygroup.remoteconfig.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import org.tinygroup.commons.tools.StringUtil;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;

/**
 * 生成客户端应用ID（ip+时间）
 * 
 * @author zhangliang08072
 * @version $Id: ClientIdUtil.java, v 0.1 2017-12-19 下午4:24:52 zhangliang08072
 *          Exp $
 */
public class ClientIdUtil {
	private static final Logger LOGGER = LoggerFactory.getLogger(ClientIdUtil.class);
	
	/**
	 * 生成客户端ID（ip+时间）或者（ip+客户端名称+时间）
	 * @param clientName 客户端名称
	 * @return
	 */
	public static String getClientId(String clientName){
		InetAddress  inetAddress = null;
		String ip = null;
		try {
			inetAddress = getLocalHostLANAddress();
			ip = inetAddress.getHostAddress();
		} catch (Exception e) {
			ip = "unkonwn_ip";
		}
		if(StringUtil.isBlank(clientName))
			return ip+"_"+getAppStartTimeStr();
		else
			return ip+"_"+clientName+"_"+getAppStartTimeStr();
	}

	public static InetAddress getLocalHostLANAddress() throws Exception {
		try {
			InetAddress candidateAddress = null;
			// 遍历所有的网络接口
			for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
					.hasMoreElements();) {
				NetworkInterface iface = (NetworkInterface) ifaces
						.nextElement();
				// 在所有的接口下再遍历IP
				for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs
						.hasMoreElements();) {
					InetAddress inetAddr = (InetAddress) inetAddrs
							.nextElement();
					if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
						if (inetAddr.isSiteLocalAddress()) {
							// 如果是site-local地址，就是它了
							return inetAddr;
						} else if (candidateAddress == null) {
							// site-local类型的地址未被发现，先记录候选地址
							candidateAddress = inetAddr;
						}
					}
				}
			}
			if (candidateAddress != null) {
				return candidateAddress;
			}
			// 如果没有发现 non-loopback地址.只能用最次选的方案
			InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
			return jdkSuppliedAddress;
		} catch (Exception e) {
			LOGGER.logMessage(LogLevel.ERROR, "客户端获取IP地址失败",e);
			throw e;
		}
	}

	private static String getAppStartTimeStr() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return formatter.format(new Date());
	}

	public static void main(String[] args) {
		System.out.println(getClientId(null));
		System.out.println(getClientId("configcenter"));
	}

}
